package com.xck.clouddisk.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xck.clouddisk.entity.User;
import com.xck.clouddisk.exception.BusinessException;
import com.xck.clouddisk.response.Result;
import com.xck.clouddisk.service.AliMsgService;
import com.xck.clouddisk.service.UserService;
import com.xck.clouddisk.utils.MD5Utils;
import com.xck.clouddisk.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Api("用户登录")
@RestController
@CrossOrigin
public class LoginController {

    @Resource
    private UserService userService;

    @Resource
    private AliMsgService aliMsgService;

    @Resource
    private RedisTemplate redisTemplate;

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result login(String phone, String password, HttpServletRequest request){
        //先判断手机号是否存在
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",phone);
        User u = userService.getOne(wrapper);
        if(StringUtils.isEmpty(u)){
            throw new BusinessException(20000,"此电话没有被注册");
        }else{
            wrapper.eq("password",password);
            u = userService.getOne(wrapper);
            if(StringUtils.isEmpty(u)){
                throw new BusinessException(20000,"你输入的密码错误");
            }else{
                request.getSession().setAttribute("user",u);
                return Result.ok().data("user",u);
            }
        }
    }

    /**
     * 注册用户
     * @return
     */
    @ApiOperation("注册用户")
    @PostMapping("/registry")
    public Result registry(User user){

        user.setIsVip(1);
        user.setDeleted(1);
        user.setSalt(UUID.randomUUID().toString().substring(0,32));
        user.setPassword(MD5Utils.md5Encryption(user.getPassword(), user.getSalt()));
        boolean save = userService.save(user);
        if(save){
            return Result.ok();
        }else{
            return Result.error();
        }
    }
}
